/*
 * tm1637.c
 *
 * Copyright 2022 dh33ex <dh33ex@riseup.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA or see <http://www.gnu.org/licenses/>.
 *
 *
 */


#ifndef __msp430_h_
    #include <msp430.h>
#endif
#include "tm1637.h"


static const unsigned char digit_HEX[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x00};

void TM1637_start(TM1637 *disp);
void TM1637_stop(TM1637 *disp);
unsigned char TM1637_send_byte(TM1637 *disp, unsigned char data);
void TM1637_send_array(TM1637 *disp, unsigned char *send_data);


void TM1637_init(TM1637 *disp) {
    P1DIR |= disp->clk;
    P1DIR |= disp->dio;
}


void TM1637_display(TM1637 *disp, unsigned char disp_data[4]) {
    unsigned char seg_data[4];
    unsigned char i;
    for (i = 0; i < 4; i++) {
        seg_data[i] = digit_HEX[disp_data[i]] + 0x80 * disp->colon;
    }
    TM1637_send_array(disp, seg_data);
}


void TM1637_send_array(TM1637 *disp, unsigned char send_data[]) {
    TM1637_start(disp);
    TM1637_send_byte(disp, 0x40);
    TM1637_stop(disp);
    TM1637_start(disp);
    TM1637_send_byte(disp, 0xC0);
    unsigned char i;
    for (i = 0; i < 4; i++) {
        TM1637_send_byte(disp, send_data[i]);
    }
    TM1637_stop(disp);
    TM1637_start(disp);
    TM1637_send_byte(disp, 0x88 + disp->brightness);
    TM1637_stop(disp);
}


void TM1637_start(TM1637 *disp) {
    P1OUT |= disp->clk;
    P1OUT |= disp->dio;
    P1OUT &= ~disp->dio;
    P1OUT &= ~disp->clk;
}


void TM1637_stop(TM1637 *disp) {
    P1OUT &= ~disp->clk;
    P1OUT &= ~disp->dio;
    P1OUT |= disp->clk;
    P1OUT |= disp->dio;
}


unsigned char TM1637_send_byte(TM1637 *disp, unsigned char data) {
    unsigned char i;
    for (i = 0; i < 8; i++) {
        P1OUT &= ~disp->clk;
        if (data & 0x01) {
            P1OUT |= disp->dio;
        } else {
            P1OUT &= ~disp->dio;
        }
        data >>= 1;
        P1OUT |= disp->clk;
    }

    P1OUT &= ~disp->clk;
    P1OUT |= disp->dio;
    P1OUT |= disp->clk;
    P1DIR &= ~disp->dio;

    __delay_cycles(1000);
    unsigned char ack = P1IN & disp->dio;
    if (ack == 0) {
        P1DIR |= disp->dio;
        P1OUT &= ~disp->dio;
    }
    __delay_cycles(1000);
    P1DIR |= disp->dio;
    __delay_cycles(1000);

    return ack;
}
